<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace App\Http\Validator;

use W7\Validate\Support\DataAttribute;
use W7\Validate\Support\ValidateScene;
use W7\Validate\Validate;

class UserValidate extends Validate
{
    protected $rule = [
        'id'       => 'required|numeric|min:1|exists:demo_users',
        'username' => 'required|alphaNum|min:3|max:18',
        'password' => 'required|min:6|max:18',
        'name'     => 'required|chsAlpha|max:20',
        'page'     => 'numeric|min:1'
    ];

    protected $customAttributes = [
        'id'       => '指定用户',
        'username' => '用户名',
        'password' => '密码',
        'name'     => '名称',
        'page'     => '页码',
    ];

    protected $scene = [
        'login'  => ['username', 'password'],
        'list'   => ['page'],
        'delete' => ['id'],
        'logout' => []
    ];

    protected function sceneAdd(ValidateScene $scene)
    {
        $scene->only(['username', 'password', 'name'])
            ->append('username', 'unique:App\Models\User,username');
    }

    protected function sceneSave(ValidateScene $scene)
    {
        $scene->only(['id', 'name', 'password'])
            ->remove('name', 'required')
            ->remove('password', 'required')
            ->default('name', 'deleteEmpty')
            ->default('password', 'deleteEmpty');
    }

    public function defaultDeleteEmpty($value, $field, $data, DataAttribute $dataAttribute)
    {
        if ('' === $value || is_null($value)) {
            $dataAttribute->deleteField = true;
        }
        return $value;
    }
}
